package com.ktjiaoyu.controller;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController{
    private static final Logger LOGGER = LoggerFactory.getLogger(SupplierController.class);
    @Autowired
    private SupplierService supplierService;
    @Autowired
    @Qualifier("uploadService") //指定注入保存到本地硬盘的上传业务实现对象
    private UploadService uploadService;



    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Map<String, Object> del(@PathVariable("id") int id){
        Map<String, Object> map = new HashMap<>();
        try{
            Boolean ren= supplierService.delete(id);
            if(ren) {
                map.put("code" , 200);
            }else {
                map.put("code", 500);
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }

    @ResponseBody
    @GetMapping("/supCodeExist")
    public Object del(@RequestParam("supCode") String supCode){
        Map<String, Object> map = new HashMap<>();
        try{
          // 角色编号不可为空
            if(StringUtils.isEmpty(supCode)){
                map.put("exist", 0);
            }else {
                Supplier supplier = supplierService.getBySupCode(supCode);
                if(null != supplier) {
                    map.put("exist", 1);
                }else {
                    map.put("exist", 0);
                }
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }
    @ResponseBody
    @GetMapping("/{id}/view")
    public Object ajaxView(@PathVariable("id") Long id) {
        Map<String, Object> map = new HashMap<>();
        try {
            Supplier supplier = supplierService.findById(id);
            if (supplier != null) {
                map.put("code", 200);
                map.put("data", supplier);
            } else {
                map.put("code", 500);
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController中的ajaxView方法执行发生错误。 ", e);
            map.put("code", 500);
        }
        return map;
    }
    @RequestMapping("/page")
    public String page(Model model, Supplier condition,
                       @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        Page<Supplier> page = null;
        try {
            //查询用户的分页信息
            page = supplierService.findPage(condition,pageNo,pageSize);
            //将分页数据,角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo",page);
            model.addAttribute("condition",condition);
        }catch (Exception e){
            LOGGER.error("SupplierController中的page方法执行发生错误.",e);
        }
        return "supplier/page";
    }

    /**跳转到save.jsp页面的接口 */
    @GetMapping("/save")
    public String toSave(Model model){
        try {
            //回显数据需要sysUser,这里给个空对象避免出错
            model.addAttribute("sysUser",new SysUser());
        }catch (Exception e){
            LOGGER.error("SupplierController中的tosave方法执行发生错误.",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }
    /** 保存或修改数据接口 */
    @PostMapping("/save")
    public String doSave(Supplier supplier, MultipartFile bizPic){
        //允许的上传图片后缀
        String[] allowImageExt = {"jpg","jpeg","png","gif","bmp"};
        try {
            //上传证件照
            if(bizPic !=null){
                //调用上传文件服务,返回上传成功后路径,为null表示没有上传
                String bizPicPath = uploadService.uploadFile(bizPic,allowImageExt);
                supplier.setBizPicPath(bizPicPath);
            }
            //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            if(supplier.getId() == null){
                //如果是添加用户,关联创建用户为当前登录用户
                supplier.setCreatedUserId(loginUser.getId());
                supplier.setCreatedTime(new Date());
            }else {
                //如果是修改用户,关联修改用户为当前登录用户
                supplier.setUpdatedUserId(loginUser.getId());
                supplier.setUpdatedTime(new Date());
            }
            //新增和修改公用同一个业务方法
            boolean ok = supplierService.saveOrUpdate(supplier);
            if(ok){
                //保存成功,跳回列表页面
                return "redirect:/main/supplier/page";
            }
        }catch (Exception e){
            LOGGER.error("SupplierController中的doSave方法执行发生错误.",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    /** 详情 */
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        Supplier supplier = null;
        try {
            supplier = supplierService.findById(id);
            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            LOGGER.error("SupplierController中的view方法执行发生错误.",e);
            throw new RuntimeException(e);
        }
        return "supplier/view";
    }

    /** 查询用户信息并跳转修改页 */
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        Supplier supplier = null;
        try {
            supplier = supplierService.findById(id);

            model.addAttribute("supplier",supplier);
        }catch (Exception e){
            LOGGER.error("SupplierController中的toEdit方法执行发生错误.",e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }
}
